<?php
namespace Addons\QyWechat\Controller\Api\Providers;
use Models\BaseModel as Model;
use Addons\QyWechat\Helper;
use Addons\Fission\Helper as FissionHelper;
use Addons\QyWechat\Services\QyWechatApi;
use Addons\QyWechat\Services\ProvidersApi;
require_once(DOXCX_FRAME_PATH . 'fun/library/QyWxCypto/WXBizMsgCrypt.php');

use Addons\WechatOpenPlatform\Services\Wxopenapi;
 
class ThirdParty extends \BaseController
{ 
    public function index(){
        if(isset($_GET['echostr'])){
            $sVerifyMsgSig = $_GET['msg_signature'];
            $sVerifyTimeStamp = $_GET['timestamp'];  
            $sVerifyNonce = $_GET['nonce'];
            $sVerifyEchoStr = $_GET['echostr'];
            $configList = (new Model('qy_party_confings'))->list_all();
            foreach($configList as $config){
                $encodingAesKey = $config->EncodingAESKey;
                $token = $config->token;
                $corpId = $config->corp_id;//需要用到企业id，目前测试
                $wxcpt = new \WXBizMsgCrypt($token, $encodingAesKey, $corpId);
                // 需要返回的明文
                $sEchoStr = "";
                $errCode = $wxcpt->VerifyURL($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $sVerifyEchoStr, $sEchoStr);
                if($errCode == 0){
                    echo $sEchoStr;
                    exit();
                }
            }
        }else{
            //搜集参数  
            $sReqMsgSig = $_GET['msg_signature'];
            $sReqTimeStamp = $_GET['timestamp'];
            $sReqNonce = $_GET['nonce'];
            //获取xml冰去除特殊字符 
            $sReqData = preg_replace("/[\n\s]/", '', file_get_contents('php://input'));
            $config = (new Model('qy_party_confings'))->find(['suite_id'=>xml_to_array($sReqData)['ToUserName']]);
            //解密
            $encodingAesKey = $config->EncodingAESKey;
            $token = $config->token;
            $corpId = $config->suite_id;
            //需要填写模板id
            $wxcpt = new \WXBizMsgCrypt($token, $encodingAesKey, $corpId);
            $sMsg = "";  // 解析之后的明文
            $errCode = $wxcpt->DecryptMsg($sReqMsgSig, $sReqTimeStamp, $sReqNonce, $sReqData, $sMsg);
            if ($errCode == 0) {
                $arr = xml_to_array($sMsg);
                switch ($arr['InfoType']){
                    case 'suite_ticket':
                        $this->save_suite_ticket($arr);
                        break;
                    case 'create_auth':
                        $this->change_auth_code($arr);
                        break;
                    case 'reset_permanent_code':
                        $this->reset_permanent_code($arr);
                        break;
                    default:
                        # code...
                        break;
                }
            } else {
                diy_log("解密失败ERR: " . $errCode . "\n\n");
            }
            echo "success";
        }
    }

    public function client(){
        $sVerifyMsgSig = $_GET['msg_signature'];
        $sVerifyTimeStamp = $_GET['timestamp'];  
        $sVerifyNonce = $_GET['nonce'];
        $sVerifyEchoStr = $_GET['echostr'];
        $configList = (new Model('qy_party_confing'))->list_all();
        $conf = (new Model('qy_party_confings'))->find(["isadmin"=>1]);
        foreach($configList as $config){
            $encodingAesKey = $conf->EncodingAESKey;
            $token = $conf->token;
            $corpId = $config->qy_appid;//需要用到企业id，目前测试
            $wxcpt = new \WXBizMsgCrypt($token, $encodingAesKey, $corpId);
            // 需要返回的明文
            $sEchoStr = "";
            $errCode = $wxcpt->VerifyURL($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $sVerifyEchoStr, $sEchoStr);
            if($errCode == 0){
                echo $sEchoStr;
                exit();
            }
        }
    }

     /**
    * 保存令牌
    **/
    private function save_suite_ticket($arr){
        //抓取suite_ticket
        $st = (new Model('qy_providers_suite_ticket'))->find(['suite_id'=>$arr['SuiteId']]);
        if(!$st->id){
            $st = new Model('qy_providers_suite_ticket');
        }
        $st->suite_id = $arr['SuiteId'];
        $st->suite_ticket = $arr['SuiteTicket'];
        $st->ctime = $arr['TimeStamp'];
        $st->save();
    }

    public function change_auth_code($arr){
        if($arr['InfoType'] == 'create_auth'){
            $this->create_auth($arr);
        }else if($arr['InfoType'] == 'change_auth'){

        }else if($arr['InfoType'] == 'cancel_auth'){

        }
        
    }

    public function create_auth($arr){
        $suite_access_token = $this->suite_access_token($arr);
        $data = [
            'auth_code' => $arr['AuthCode']
        ];
        $res = \HttpCurl::post("https://qyapi.weixin.qq.com/cgi-bin/service/get_permanent_code?suite_access_token=".$suite_access_token,
            json_encode($data)
        );
        $res_arr = json_decode($res,1);
        $configs = (new Model('qy_party_confing'))->find(['qy_appid'=>$res_arr["auth_corp_info"]["corpid"]]);
        $configs->permanent_code = $res_arr["permanent_code"];
        $configs->data = json_encode($res_arr,320);
        $configs->save();
    }
    
    public function reset_permanent_code($arr){
        $suite_access_token = $this->suite_access_token($arr);
        $data = [
            'auth_code' => $arr['AuthCode']
        ];
        $res = \HttpCurl::post("https://qyapi.weixin.qq.com/cgi-bin/service/get_permanent_code?suite_access_token=".$suite_access_token,
            json_encode($data)
        );
        $res_arr = json_decode($res,1);
        $configs = (new Model('qy_party_confing'))->find(['qy_appid'=>$res_arr["auth_corp_info"]["corpid"]]);
        $configs->permanent_code = $res_arr["permanent_code"];
        $configs->data = json_encode($res_arr,320);
        $configs->save();
    }

    public function suite_access_token($arr){
        $config = (new Model('qy_party_confings'))->find(['suite_id'=>$arr['SuiteId']]);
        $st = (new Model('qy_providers_suite_ticket'))->find(['suite_id'=>$arr['SuiteId']]);
        $sat = (new Model('qy_party_token'))->find(['suite_id'=>$arr['SuiteId']]);
        if(!$sat->suite_token || time() - $sat->ctime > 7000){
            $data = [
                'suite_id' => $config->suite_id,
                'suite_secret' => $config->suite_secret,
                'suite_ticket' => $st->suite_ticket
            ];
            $res = \HttpCurl::post("https://qyapi.weixin.qq.com/cgi-bin/service/get_suite_token",
                json_encode($data)
            );
            $res_arr = json_decode($res,1);
            if($res_arr['errcode'] == 0){
                $sat->suite_token = $res_arr['suite_access_token'];
                $sat->suite_id = $arr['SuiteId'];
                $sat->ctime = time();
                $sat->save();
            }
        }
        return $sat->suite_token;
    }
}
    